<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <a-form layout="horizontal">
        <div :class="advanced ? null: 'fold'">
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item label='单据时间'
                           :labelCol="{span: 4}"
                           :wrapperCol="{span: 18}">
                <a-range-picker @change="rangeDateChange" v-decorator="['billDate']"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label='厂家名称'
                           :labelCol="{span: 4}"
                           :wrapperCol="{span: 15, offset: 2}">
                <a-input v-model="queryParams.supper"/>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <span style="float: right; margin-top: 3px;">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </span>
      </a-form>
    </div>
    <div>
      <div class="option-area">
        <div class="upload-area">
          <a-button type="primary" ghost @click="add">新增</a-button>
          <a-button @click="batchDelete" v-hasPermission="'user:delete'">删除</a-button>
          <a-button @click="approve">提交审批</a-button>
        </div>
      </div>
      <!--      <process-start
              ref="processStart"
              @on-loading="processLoading=true"
              @on-loaded="processLoading=false"
            />-->
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :scroll="{ x: 900 }"
               bordered
               @change="handleTableChange">
        <template slot="operation" slot-scope="text, record">
          <a-icon v-hasPermission="'user:update'" type="setting" theme="twoTone" twoToneColor="#4a9ff5"
                  @click="edit(record)" title="编辑物资入库"></a-icon>
          <a-icon type="eye" theme="twoTone" twoToneColor="#42b983" @click="view(record)" title="查看"></a-icon>
          <!--<a-badge v-hasNoPermission="'user:update','user:view'" status="warning" text="无权限"></a-badge>-->
        </template>
      </a-table>
    </div>
    <!-- 新增用户 -->
    <materialin-add
      @close="handleUserAddClose"
      @success="handleUserAddSuccess"
      :budgetAddVisiable="MaterialinAdd.visiable">
    </materialin-add>
    <!-- 编辑 -->
    <materialin-edit
      ref="monthlyBudgetEdit"
      @close="handleMonthBudgetClose"
      @success="handleBudgetEditSuccess"
      :budgetEditVisiable="MaterialinEdit.visiable">
    </materialin-edit>
    <!-- 用户信息查看 -->
    <materialin-info
      :budgetInfoData="MaterialinInfo.data"
      :userInfoVisiable="MaterialinInfo.visiable"
      @close="handleBudGetInfoClose">
    </materialin-info>
  </a-card>
</template>

<script>
/*  import processStart from '@/components/act/process-start'*/
import MaterialinAdd from './materialinAdd'
import MaterialinEdit from './materialinEdit'
import MaterialinInfo from './materialinInfo'
import RangeDate from '@/components/datetime/RangeDate'
import moment from 'moment'

moment.locale('zh-cn')
//对外给出组件
export default {
  name: 'AnnualBudget',
  components: {RangeDate, MaterialinAdd, MaterialinEdit, MaterialinInfo},
  data () {
    return {
      rangDate: [],
      advanced: false,
      MaterialinAdd: {
        visiable: false
      },
      MaterialinInfo: {
        visiable: false,
        data: {}
      },
      MaterialinEdit: {
        visiable: false
      },
      queryParams: {
        budgetMonth: new Date(),
        supper: ''
      },
      queryForm: {},
      filteredInfo: null,
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      selectedRowKeys: [],
      loading: false,
      procInstId: '',
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      }
    }
  },
  computed: {
    columns () {
      let {sortedInfo, filteredInfo} = this
      sortedInfo = sortedInfo || {}
      filteredInfo = filteredInfo || {}
      return [{
        title: '序号',
        width: 80,
        customRender: function (text, record, index) {
          return index + 1
        }
      }, {
        title: '单据日期',
        dataIndex: 'billDate'
      }, {
        title: '单据编号',
        dataIndex: 'billCode'
      }, {
        title: '厂家名称',
        dataIndex: 'supper',
      }, {
        title: '仓库名称',
        dataIndex: 'storeName',
      }, {
        title: '单据状态',
        dataIndex: 'billStatus',
        customRender: (text, row, index) => {
          switch (text.trim()) {
            case '0':
              return <a-tag color="red">新建</a-tag>
            case '1':
              return <a-tag color="cyan">审批</a-tag>
            default:
              return <a-tag color='yellow'>结束</a-tag>
          }
        },
      }, {
        title: '单据金额',
        dataIndex: 'billAmount'
      }, {
        title: '保管员',
        dataIndex: 'storeKeeper'
      }, {
        title: '确认人',
        dataIndex: 'comfirmName'
      }, {
        title: '确认时间',
        dataIndex: 'comfirmTime'
      }, {
        title: '操作',
        dataIndex: 'operation',
        scopedSlots: {customRender: 'operation'}
      }
      ]
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      this.type = this.$route.query.type
      this.backRoute = this.$route.query.backRoute
      this.queryForm = this.$route.query
      if (this.type != 0 && this.type) {
        this.queryParams.id = this.$route.query.id
        this.fetch({
          ...this.queryParams
        })
      } else {
        this.fetch()
      }
    },
    rangeDateChange (value) {
      this.rangDate = value
    },
    view (record) {
      this.$get('materialindetail', {'materialInId': record.id}).then((res) => {
        this.MaterialinInfo.data = res.data
      })
      this.MaterialinInfo.visiable = true
    },

    handleMonthBudgetClose () {
      this.MaterialinEdit.visiable = false
    },
    handleBudgetEditSuccess () {
      this.MaterialinEdit.visiable = false
      this.$message.success('编辑成功')
      this.search()
    },
    handleBudGetInfoClose () {
      this.MaterialinInfo.visiable = false
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    add () {
      this.MaterialinAdd.visiable = true
    },
    handleUserAddClose () {
      this.MaterialinAdd.visiable = false
    },
    handleUserAddSuccess () {
      this.MaterialinAdd.visiable = false
      this.$message.success('新增成功')
      this.search()
    },
    edit (record) {
      this.$refs.monthlyBudgetEdit.setFormValues(record, this.type, this.queryForm)
      this.MaterialinEdit.visiable = true
    },

    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let ids = []
          for (let key of that.selectedRowKeys) {
            ids.push(that.dataSource[key].id)
          }
          that.$delete('materialIn', {'bid': ids.join(',')}).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.search()
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    search () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      // 清空部门树选择
      this.$refs.deptTree.reset()
      // 清空时间选择
      if (this.advanced) {
        this.$refs.createTime.reset()
      }
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这两个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.sortedInfo = sorter
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch (params = {}) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      if (typeof this.rangDate !== 'undefined' && this.rangDate.length > 1) {
        params.stime = this.rangDate[0].format('YYYY-MM-DD')
        params.etime = this.rangDate[1].format('YYYY-MM-DD')
      }
      if (typeof params.supper == 'undefined') params.supper = ''
      this.$get('materialIn',
        params
      ).then((r) => {
        let data = r.data
        for (let i = 0; i < data.rows.length; i++) {
          let time = null
          time = data.rows[i].billDate.slice(0, 10)
          data.rows[i].billDate = time
        }
        const pagination = {...this.pagination}
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        this.loading = false
      })
    },
    approve () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要提交的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定提交所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被提交审核',
        centered: true,
        onOk () {
          let ids = []
          for (let key of that.selectedRowKeys) {
            ids.push(that.dataSource[key].id)
          }
          let key = {'list': ids.join(',')}
          that.$refs.processStart.show('materialin', key)
          that.$put('materialIn/profile', key).then(() => {
            that.$message.success('提交成功')
            that.selectedRowKeys = []
            that.fetch()
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
  }
}
</script>
<style lang="less" scoped>

.option-area {
  display: inline-block;
  width: 100%;
  padding: 0 .9rem;
  margin: .5rem 0;

  .upload-area {
    display: inline;
    float: left;
    width: 50%
  }

  .button-area {
    margin-left: 1rem;
    display: inline;
    float: right;
    width: 20%;
  }

}
</style>
